class ClientesController < ApplicationController
  before_filter :authorize, :only => [:show, :edit, :update]
  before_filter :authorize_admin, :only => [:index]

  # GET /clientes
  # GET /clientes.json
  def index
    @clientes = Cliente.paginate( :page => params[:page],
                                  :per_page => 3).order(:nombre)

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @clientes }
    end
  end

  # GET /clientes/1
  # GET /clientes/1.json
  def show
    @cliente = Cliente.find(params[:id])
    @cliente_actual = Cliente.find_by_id(session[:cliente_id])
    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @cliente }
    end
  end

  # GET /clientes/new
  # GET /clientes/new.json
  def new
    @cliente = Cliente.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @cliente }
    end
  end

  # GET /clientes/1/edit
  def edit
    @cliente = Cliente.find(params[:id])
    @cliente_actual = Cliente.find_by_id(session[:cliente_id])
  end

  # POST /clientes
  # POST /clientes.json
  def create
    @cliente = Cliente.new(params[:cliente])
    @cart = Carrito.new
    @cart.cliente = @cliente
    
    respond_to do |format|
      if @cliente.save && @cart.save
        format.html { redirect_to @cliente, notice: 'Cliente was successfully created.' }
        format.json { render json: @cliente, status: :created, location: @cliente }
      else
        format.html { render action: "new" }
        format.json { render json: @cliente.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /clientes/1
  # PUT /clientes/1.json
  def update
    @cliente = Cliente.find(params[:id])

    respond_to do |format|
      if @cliente.update_attributes(params[:cliente])
        format.html { redirect_to @cliente, notice: 'Cliente was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @cliente.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /clientes/1
  # DELETE /clientes/1.json
  def destroy
    @cliente = Cliente.find(params[:id])
    @cliente_actual = Cliente.find_by_id(session[:cliente_id])
    
    begin
      @cliente.destroy
      flash[:notice] = "Usuario #{@cliente.nombre} Eliminado"
    rescue Exception => e
      flash[:notice] = e.message
    end

    if @cliente = @cliente_actual
      reset_session  

      respond_to do |format|
        format.html { redirect_to tienda_url }
        format.json { head :no_content }
      end
    else
      respond_to do |format|
        format.html { redirect_to clientes_url }
        format.json { head :no_content }      
      end     
    end 
  end
end
